// HTTP 性能测试运行器
// @/utils/http/testRunner.ts

import { HttpClient } from './HttpClient'
import { runHttpPerformanceTest, quickPerformanceTest } from './PerformanceTest'

// 创建测试用的 HTTP 客户端
function createTestHttpClient() {
  return new HttpClient({
    baseURL: 'http://localhost:3000', // 可以配置为你的测试服务器
    timeout: 10000,
    enableCache: true,
    maxConcurrent: 10,
    retryConfig: {
      count: 3,
      delay: 1000,
      enableExponentialBackoff: true
    }
  })
}

// 在浏览器控制台中运行完整测试
export async function runFullPerformanceTest() {
  console.log('🔥 启动完整 HTTP 性能测试...')
  console.log('📝 请在浏览器控制台中查看详细结果')
  
  const httpClient = createTestHttpClient()
  
  try {
    await runHttpPerformanceTest(httpClient)
    console.log('🎉 性能测试完成！')
  } catch (error) {
    console.error('❌ 性能测试失败:', error)
  } finally {
    httpClient.destroy()
  }
}

// 运行快速测试
export async function runQuickTest() {
  console.log('⚡ 启动快速性能测试...')
  
  const httpClient = createTestHttpClient()
  
  try {
    await quickPerformanceTest(httpClient)
    console.log('✅ 快速测试完成！')
  } catch (error) {
    console.error('❌ 快速测试失败:', error)
  } finally {
    httpClient.destroy()
  }
}

// 在页面中显示性能测试按钮的帮助函数
export function addPerformanceTestButtons() {
  // 只在开发环境中添加
  if (process.env.NODE_ENV !== 'development') {
    return
  }
  
  // 创建测试按钮容器
  const container = document.createElement('div')
  container.style.cssText = `
    position: fixed;
    top: 10px;
    right: 10px;
    z-index: 9999;
    background: rgba(0,0,0,0.8);
    color: white;
    padding: 10px;
    border-radius: 5px;
    font-family: monospace;
    font-size: 12px;
  `
  
  // 快速测试按钮
  const quickButton = document.createElement('button')
  quickButton.textContent = '⚡ 快速测试'
  quickButton.style.cssText = `
    margin: 5px;
    padding: 5px 10px;
    background: #007acc;
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
  `
  quickButton.onclick = () => {
    runQuickTest()
  }
  
  // 完整测试按钮
  const fullButton = document.createElement('button')
  fullButton.textContent = '🔥 完整测试'
  fullButton.style.cssText = `
    margin: 5px;
    padding: 5px 10px;
    background: #ff6b6b;
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
  `
  fullButton.onclick = () => {
    runFullPerformanceTest()
  }
  
  // 关闭按钮
  const closeButton = document.createElement('button')
  closeButton.textContent = '✕'
  closeButton.style.cssText = `
    position: absolute;
    top: 5px;
    right: 5px;
    width: 20px;
    height: 20px;
    background: transparent;
    color: white;
    border: none;
    cursor: pointer;
  `
  closeButton.onclick = () => {
    document.body.removeChild(container)
  }
  
  const title = document.createElement('div')
  title.textContent = 'HTTP 性能测试'
  title.style.marginBottom = '10px'
  
  container.appendChild(closeButton)
  container.appendChild(title)
  container.appendChild(quickButton)
  container.appendChild(fullButton)
  
  document.body.appendChild(container)
}

// 命令行测试函数（用于Node.js环境）
export async function runCLITest() {
  console.log('🚀 HTTP 性能测试 - 命令行模式')
  
  const httpClient = createTestHttpClient()
  
  try {
    // 检查是否传入了参数
    const args = process.argv.slice(2)
    
    if (args.includes('--quick')) {
      await quickPerformanceTest(httpClient)
    } else {
      await runHttpPerformanceTest(httpClient)
    }
    
    console.log('🎊 测试完成，感谢使用！')
  } catch (error) {
    console.error('💥 测试过程中出现错误:', error)
    process.exit(1)
  } finally {
    httpClient.destroy()
  }
}

// 性能基准测试 - 比较优化前后的性能
export async function benchmarkTest() {
  console.log('📊 运行性能基准测试...')
  
  const iterations = 100
  
  // 测试 1: 基础请求性能
  console.log('\n1️⃣ 基础请求性能测试')
  const startTime1 = performance.now()
  
  for (let i = 0; i < iterations; i++) {
    // 模拟请求
    await new Promise(resolve => setTimeout(resolve, Math.random() * 10))
  }
  
  const time1 = performance.now() - startTime1
  console.log(`   完成 ${iterations} 次模拟请求耗时: ${time1.toFixed(2)}ms`)
  console.log(`   平均每次请求: ${(time1 / iterations).toFixed(2)}ms`)
  
  // 测试 2: 缓存键生成性能
  console.log('\n2️⃣ 缓存键生成性能测试')
  const startTime2 = performance.now()
  
  const testData = { id: 1, name: 'test', nested: { value: 'data' } }
  for (let i = 0; i < iterations * 10; i++) {
    const cacheKey = `GET:/api/test/${i}:${JSON.stringify(testData)}`
  }
  
  const time2 = performance.now() - startTime2
  console.log(`   完成 ${iterations * 10} 次缓存键生成耗时: ${time2.toFixed(2)}ms`)
  console.log(`   平均每次生成: ${(time2 / (iterations * 10)).toFixed(4)}ms`)
  
  // 测试 3: 并发处理性能
  console.log('\n3️⃣ 并发处理性能测试')
  const startTime3 = performance.now()
  
  const promises = []
  for (let i = 0; i < 50; i++) {
    promises.push(new Promise(resolve => setTimeout(resolve, Math.random() * 50)))
  }
  
  await Promise.all(promises)
  
  const time3 = performance.now() - startTime3
  console.log(`   完成 50 个并发任务耗时: ${time3.toFixed(2)}ms`)
  
  // 性能评分
  console.log('\n🏆 性能评分:')
  const score1 = Math.max(0, 100 - (time1 / iterations))
  const score2 = Math.max(0, 100 - (time2 / (iterations * 10)) * 1000)
  const score3 = Math.max(0, 100 - time3 / 10)
  
  console.log(`   基础请求性能: ${score1.toFixed(1)}/100`)
  console.log(`   缓存键生成性能: ${score2.toFixed(1)}/100`)
  console.log(`   并发处理性能: ${score3.toFixed(1)}/100`)
  
  const totalScore = (score1 + score2 + score3) / 3
  console.log(`   📈 综合性能评分: ${totalScore.toFixed(1)}/100`)
  
  if (totalScore >= 80) {
    console.log('   🌟 性能优秀！')
  } else if (totalScore >= 60) {
    console.log('   👍 性能良好')
  } else {
    console.log('   ⚠️ 需要优化')
  }
}

// 导出测试工具函数
export const HttpTestUtils = {
  runQuickTest,
  runFullPerformanceTest,
  benchmarkTest,
  addPerformanceTestButtons,
  createTestHttpClient
}

// 如果在Node.js环境中直接运行此文件
if (typeof window === 'undefined' && require.main === module) {
  runCLITest()
} 